import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

// todo 整合user.service 功能,修改的数据可以同步修改所有子模块和父模块,比如修改用户头像
@Injectable({
    providedIn: 'root'
})
export class CacheService {
    private cacheMode: 'localStorage' | 'sessionStorage' = 'sessionStorage';

    constructor(private http: HttpClient) {
    }

    get(key: string) {
        if (key[0] === '/') {
            return new Promise((resolve, reject) => {
                const data = sessionStorage.getItem(key);
                if (data) {
                    resolve(JSON.parse(data));
                } else {
                    this.http.get(key).toPromise()
                        .then(res => {
                            if (res['status'] === 200) {
                                sessionStorage.setItem(key, JSON.stringify(res['data']));
                                resolve(res['data']);
                            } else {
                                resolve('');
                                console.error(`${key}获取数据失败`);
                                console.error(res['message']);
                            }
                        })
                        .catch(err => {
                            console.error(`${key}获取数据失败`);
                            console.error(err);
                            resolve('');
                        })
                }

            })
        } else {
            return JSON.parse(window[this.cacheMode].getItem(key));
        }
    }

    set(key: string, data: any) {
        if (key[0] === '/') {
            sessionStorage.setItem(key, JSON.stringify(data));
        } else {
            window[this.cacheMode].setItem(key, JSON.stringify(data));
        }
    }

    remove(key: string) {
        if (key[0] === '/') {
            sessionStorage.removeItem(key);
        } else {
            window[this.cacheMode].removeItem(key);
        }
    }

    clear() {
        window[this.cacheMode].clear();
    }


}
